package com.ztn.iot.zhonghaichi2.fun;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ztn.base.util.common.*;
import com.ztn.iot.zhonghaichi2.entity.SiteEntity;
import com.ztn.iot.zhonghaichi2.properties.ZhcProperties;
import com.ztn.iot.zhonghaichi2.properties.ZhcProperties2;
import com.ztn.iot.zhonghaichi2.push.CameraPushApi;
import com.ztn.iot.zhonghaichi2.push2.CameraPushApi2;
import com.ztn.iot.zhonghaichi2.push2.DataPushApi2;
import com.ztn.iot.zhonghaichi2.push2.TokenUtil;
import com.ztn.iot.zhonghaichi2.push2.req.DataReq2;
import com.ztn.iot.zhonghaichi2.push2.res.CameraRes;
import com.ztn.iot.zhonghaichi2.service.IIotDeviceService;
import com.ztn.iot.zhonghaichi2.service.ISiteService;
import com.ztn.iot.zhonghaichi2.util.LocalFileUtilImpl;
import com.ztn.sdk.iot.api.res.BaseRes;
import com.ztn.sdk.iot.api.util.HttpTool;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@EnableScheduling
@Component
public class CameraFun {

    @Autowired
    private CameraPushApi cameraPushApi;

    @Autowired
    private CameraPushApi2 cameraPushApi2;

    @Autowired
    private LocalFileUtilImpl localFileUtil;

    @Autowired
    private IIotDeviceService iotDeviceService;

    @Autowired
    private ISiteService siteService;

    @Autowired
    private ZhcProperties zhcProperties;

    @Autowired
    private ZhcProperties2 zhcProperties2;

    @PostConstruct
    public void init() {
//        pushPicture();
//        new Thread(()->{
//            while (true) {
//                try {
//                    testOne();
//                    Thread.sleep(20 * 60 * 1000);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } catch (NoSuchAlgorithmException e) {
//                    e.printStackTrace();
//                } catch (InvalidKeyException e) {
//                    e.printStackTrace();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
    }


    @Scheduled(cron = "0 0 0/2 * * ? ")
    public void snap() {
        new Thread(() -> {
            pushPicture();
        }).start();

    }

    @Data
    public static class ListCameraReq {
        private String deviceCore;
    }

    @Data
    public static class Camera {

        private Integer cameraId;

        private String hid;

        private String port;
    }

    //再肚水库-S1875
//    public void testOne() throws IOException, NoSuchAlgorithmException, InvalidKeyException {
//        long longTime = TimeTool.longTime();
//        File file = new File("./a.png");
//        String deviceId = "gw2023_44520350108-A5_91";
//        String deviceSecret = "7zg/Eh4LXnjrHCTOQAHhj5skhbo35StVWGOuharUo5U=";
//        String deviceCode = "SolarDev_S1875";
//        String sip = "44520350542001083503";
//        CameraRes push = cameraPushApi2.push(deviceId, deviceSecret,file );
//        log.warn("gw2023_44520350108-A5_91 {} {}",push,file.length());
//
//
//        CameraRes cameraRes = cameraPushApi2.push(deviceId, deviceSecret, file);
//        if (null == cameraRes || null == cameraRes.getData() || null == cameraRes.getData().getUuid()) {
//            return;
//        }
//
//
//        String resourceName = "products/" + zhcProperties2.getProductId() + "/devices/" + deviceId;
//        String expirationTime = System.currentTimeMillis() / 1000 + 100 * 24 * 60 * 60 + "";
//        String accessKey = deviceSecret;
//        String token = null;
//        try {
//            token = TokenUtil.assembleToken(zhcProperties2.getVersion(), resourceName, expirationTime, zhcProperties2.getSignatureMethod(), accessKey);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        if (null == token) {
//            return;
//        }
//
//
//        Map<String, Object> header = new HashMap<>(3);
//        header.put("token", token);
//
//        List<DataReq2.ParamsDTO.CollectedDataDTO.ValueDTO> valueDTOList = new ArrayList<>();
//
//
//        //图片 FF50H
//        DataReq2.ParamsDTO.CollectedDataDTO.ValueDTO lastHourRainCountValue = new DataReq2.ParamsDTO.CollectedDataDTO.ValueDTO();
//        lastHourRainCountValue.setIdentifier("FF50H");
//        lastHourRainCountValue.setRawValue(cameraRes.getData().getUuid());
//        lastHourRainCountValue.setValue(0D);
//        lastHourRainCountValue.setCollectTime(longTime);
//        lastHourRainCountValue.setAddr(sip);
//        lastHourRainCountValue.setOther("3");
//        lastHourRainCountValue.setEquipmentModel(deviceCode);
//        lastHourRainCountValue.setDrawingNum("3");
//        valueDTOList.add(lastHourRainCountValue);
//
//
//        DataReq2.ParamsDTO.CollectedDataDTO collectedDataDTO = new DataReq2.ParamsDTO.CollectedDataDTO();
//        collectedDataDTO.setValue(valueDTOList);
//
//        DataReq2.ParamsDTO paramsDTO = new DataReq2.ParamsDTO();
//        paramsDTO.setVersion(new DataReq2.ParamsDTO.VersionDTO("1.0"));
//        paramsDTO.setTime(new DataReq2.ParamsDTO.TimeDTO(longTime));
//        paramsDTO.setGatewayCode(new DataReq2.ParamsDTO.GatewayCodeDTO(deviceId));
//        paramsDTO.setGatewayType(new DataReq2.ParamsDTO.GatewayTypeDTO("ROUT-300"));
//        paramsDTO.setCollectedData(collectedDataDTO);
//
//        DataReq2 dataReq2 = new DataReq2();
//        dataReq2.setId(String.valueOf(IdTool.getInt()));
//        dataReq2.setVersion("1.0");
//        dataReq2.setParams(paramsDTO);
//
//        String url2 = DataPushApi2.BASE_URL + "?topic=$sys/" + zhcProperties2.getProductId() + "/" + deviceId + "/thing/property/post&protocol=" + zhcProperties2.getProtocol();
//        String reqStr = JsonTool.toJson(dataReq2);
//        log.info("url={}",url2);
//        log.info("req={}",reqStr);
//        String s = HttpClientTool.postJsonStrWithHeaderForStr(url2, reqStr, header, null);
//        log.info("res={}", s);
//    }

    public void pushPicture() {
        log.info("开始抓拍");
        long longTime = TimeTool.longTime();
        iotDeviceService.listAll().forEach(iotDeviceEntity -> {
            final SiteEntity siteEntity = siteService.get(iotDeviceEntity.getSiteId());
            if (null == siteEntity) {
                log.error("null == siteEntity {}", iotDeviceEntity.getSiteId());
                return;
            }
            ListCameraReq listCameraReq = new ListCameraReq();
            listCameraReq.setDeviceCore(iotDeviceEntity.getDeviceCore());
            BaseRes<List<Camera>> res = HttpTool.doPost("camera/bind/list", JsonTool.toJson(listCameraReq), new TypeReference<BaseRes<List<Camera>>>() {
            });
            if (null != res && null != res.data) {
                res.data.forEach(cam -> {
//                    if(!cam.getHid().equals("J14020593")){
//                        return;
//                    }
                    FileInputStream inputStream = null;
                    File file = null;
                    try {
                        String url = HttpTool.BASE_URL + "camera/snap?hid=" + cam.getHid() + "&access-token=" + HttpTool.token;
                        log.info("snap {}", url);

                        String filePath = "." + File.separator + cam.getHid() + ".png";
                        file = new File(filePath);
                        if (file.exists()) {
                            file.delete();
                        }
                        if (!HttpClientTool.getForFile(url, filePath, null)) {
                            log.error("null == file");
                            return;
                        }
                        file = new File(filePath);
                        inputStream = new FileInputStream(file);
                        byte[] snap = inputStream.readAllBytes();
                        if (null == snap || snap.length < 1000) {
                            if (null == snap) {
                                log.error("null == snap {} {}", cam.getHid(), cam.getPort());
                            } else {
                                log.error("snap error {} {} {}", cam.getHid(), cam.getPort(), new String(snap));
                            }
                            return;
                        }
                        if (null != zhcProperties.getSavePicture() && zhcProperties.getSavePicture()) {
                            localFileUtil.insert("camera", File.separator + "picture" + File.separator + siteEntity.getSiteCode() + File.separator + TimeTool.time() + ".png", snap);
                        }
                        String base64Str = ImageTool.encodeBytesToBase64(snap);
                        if (!StringUtils.hasText(base64Str)) {
                            log.error("!StringUtils.hasText(base64Str) {} {}", cam.getHid(), cam.getPort());
                        }
                        cameraPushApi.pushPicture(siteEntity.getSiteCode(), base64Str);
                        log.info("success push picture {}", siteEntity.getSiteCode());
                        if (StringUtils.hasText(iotDeviceEntity.getDeviceId()) && StringUtils.hasText(iotDeviceEntity.getDeviceSecret())) {

                            String deviceId = iotDeviceEntity.getDeviceId();
                            String deviceSecret = iotDeviceEntity.getDeviceSecret();

                            CameraRes cameraRes = cameraPushApi2.push(deviceId, deviceSecret, file);
                            if (null == cameraRes || null == cameraRes.getData() || null == cameraRes.getData().getUuid()) {
                                return;
                            }


                            String resourceName = "products/" + zhcProperties2.getProductId() + "/devices/" + deviceId;
                            String expirationTime = System.currentTimeMillis() / 1000 + 100 * 24 * 60 * 60 + "";
                            String accessKey = deviceSecret;
                            String token = null;
                            try {
                                token = TokenUtil.assembleToken(zhcProperties2.getVersion(), resourceName, expirationTime, zhcProperties2.getSignatureMethod(), accessKey);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            if (null == token) {
                                return;
                            }


                            Map<String, Object> header = new HashMap<>(3);
                            header.put("token", token);

                            List<DataReq2.ParamsDTO.CollectedDataDTO.ValueDTO> valueDTOList = new ArrayList<>();


                            //图片 FF50H
                            DataReq2.ParamsDTO.CollectedDataDTO.ValueDTO lastHourRainCountValue = new DataReq2.ParamsDTO.CollectedDataDTO.ValueDTO();
                            lastHourRainCountValue.setIdentifier("FF50H");
                            lastHourRainCountValue.setRawValue(cameraRes.getData().getUuid());
                            lastHourRainCountValue.setValue(0D);
                            lastHourRainCountValue.setCollectTime(longTime);
                            lastHourRainCountValue.setAddr(iotDeviceEntity.getCameraSip());
                            lastHourRainCountValue.setOther("3");
                            lastHourRainCountValue.setEquipmentModel(iotDeviceEntity.getDeviceCore());
                            lastHourRainCountValue.setDrawingNum("3");
                            valueDTOList.add(lastHourRainCountValue);


                            DataReq2.ParamsDTO.CollectedDataDTO collectedDataDTO = new DataReq2.ParamsDTO.CollectedDataDTO();
                            collectedDataDTO.setValue(valueDTOList);

                            DataReq2.ParamsDTO paramsDTO = new DataReq2.ParamsDTO();
                            paramsDTO.setVersion(new DataReq2.ParamsDTO.VersionDTO("1.0"));
                            paramsDTO.setTime(new DataReq2.ParamsDTO.TimeDTO(longTime));
                            paramsDTO.setGatewayCode(new DataReq2.ParamsDTO.GatewayCodeDTO(deviceId));
                            paramsDTO.setGatewayType(new DataReq2.ParamsDTO.GatewayTypeDTO("ROUT-300"));
                            paramsDTO.setCollectedData(collectedDataDTO);

                            DataReq2 dataReq2 = new DataReq2();
                            dataReq2.setId(String.valueOf(IdTool.getInt()));
                            dataReq2.setVersion("1.0");
                            dataReq2.setParams(paramsDTO);

                            String url2 = DataPushApi2.BASE_URL + "?topic=$sys/" + zhcProperties2.getProductId() + "/" + deviceId + "/thing/property/post&protocol=" + zhcProperties2.getProtocol();
                            String resStr = JsonTool.toJson(dataReq2);
                            String s = HttpClientTool.postJsonStrWithHeaderForStr(url2, resStr, header, null);
                            log.info("res {}", s);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (null != inputStream) {
                            try {
                                inputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (null != file) {
                            file.delete();
                        }
                    }
                });
            } else {
                log.error("get device camera list worry");
            }
        });
    }


}
